package com.thiswhyme.common.utils.json.gson.typeadapter;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;

/**
 * @description: Instant序列化器
 * @author: thiswhyme
 * @date: 2020/9/17
 */
public class InstantSerializer implements JsonSerializer<Instant>, JsonDeserializer<Instant> {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private String dateFormat;

    /**
     * 默认构造器
     */
    public InstantSerializer() {
        this(DEFAULT_PATTERN);
    }

    /**
     * 指定格式的构造函数
     * @param dateFormat
     */
    public InstantSerializer(String dateFormat) {
        super();
        this.dateFormat = dateFormat;
    }

    public String getDateFormat() {
        return this.dateFormat;
    }

    private SimpleDateFormat formatter() {
        return new SimpleDateFormat(this.dateFormat);
    }

    @Override
    public Instant deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Instant instant = null;
        if (null != json) {
            try {
                instant = formatter().parse(json.getAsString()).toInstant();
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
        return instant;
    }

    @Override
    public JsonElement serialize(Instant instant, Type typeOfSrc, JsonSerializationContext context) {
        String value = "";
        if (instant != null) {
            value = formatter().format(new Date(instant.toEpochMilli()));
        }
        return new JsonPrimitive(value);
    }
}
